package com.sjgl.esdn.controller;

import com.sjgl.esdn.constant.UserConstantsESDN;
import com.sjgl.esdn.domain.AjaxResultESDN;
import com.sjgl.esdn.domain.entity.File;
import com.sjgl.esdn.domain.entity.Question;
import com.sjgl.esdn.domain.entity.User;
import com.sjgl.esdn.domain.entity.vo.ResetPasswordRequest;
import com.sjgl.esdn.service.BoxroomService;
import com.sjgl.esdn.service.DeptService;
import com.sjgl.esdn.service.FileService;
import com.sjgl.esdn.service.UserService;
import com.sjgl.esdn.utils.ImageUtilsESDN;
import com.sjgl.esdn.utils.SecurityUtilsESDN;
import com.sjgl.esdn.utils.StringUtilsESDN;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户 控制层
 *
 * @author Administrator
 * @date 2022/08/01
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseControllerESDN {
    @Autowired
    UserService userService;

    @Autowired
    FileService fileService;

    @Autowired
    DeptService deptService;

    @Autowired
    BoxroomService boxroomService;

    @Autowired
    BoxroomController boxroomController;

    /**
     * 获取用户列表（多条件查询）
     *
     * @return {@link List}<{@link User}>
     */
    @RequestMapping("/list")
    public AjaxResultESDN selectUserList(@RequestBody User user) {
        AjaxResultESDN ajax = AjaxResultESDN.success();
        List<User> users = userService.selectUserList(user);
        ajax.put(AjaxResultESDN.DATA_TAG, users);
        return ajax;
    }

    /**
     * 获取用户详细信息
     */
    @GetMapping(value = {"/getById/{userId}"})
    public AjaxResultESDN getUser(@PathVariable(value = "userId", required = true) Long userId) {
        AjaxResultESDN ajax = AjaxResultESDN.success();
        if (StringUtilsESDN.isNotNull(userId)) {
            User user = userService.selectUserById(userId);
            ajax.put(AjaxResultESDN.DATA_TAG, user);
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PostMapping("/add")
    public AjaxResultESDN add(@RequestBody User user) {
        if (UserConstantsESDN.NOT_UNIQUE.equals(userService.checkUserUnique(user.getUserId()))) {
            return AjaxResultESDN.error("新增用户'" + user.getUserId() + "'失败，工号已存在");
        } else if (StringUtilsESDN.isNotEmpty(user.getPhonenumber())
                && UserConstantsESDN.NOT_UNIQUE.equals(userService.checkPhoneUnique(user.getPhonenumber()))) {
            return AjaxResultESDN.error("新增用户'" + user.getUserId() + "'失败，手机号码已存在");
        } else if (StringUtilsESDN.isNotEmpty(user.getDeptName())
                && deptService.checkDeptUnique(user.getDeptName())) {
            return AjaxResultESDN.error("新增用户'" + user.getUserId() + "'失败，部门不存在");
        }

        user.setPassword(SecurityUtilsESDN.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PutMapping("/update")
    public AjaxResultESDN update(@Validated @RequestBody User user) {
        //权限，待办
        if (StringUtilsESDN.isNotEmpty(user.getPhonenumber())
                && UserConstantsESDN.NOT_UNIQUE.equals(userService.checkPhoneUnique(user.getPhonenumber()))) {
            return AjaxResultESDN.error("修改用户'" + user.getUserId() + "'失败，手机号码已存在");
        } else if (StringUtilsESDN.isNotEmpty(user.getEmail())
                && UserConstantsESDN.NOT_UNIQUE.equals(userService.checkEmailUnique(user.getEmail()))) {
            return AjaxResultESDN.error("修改用户'" + user.getUserId() + "'失败，邮箱账号已存在");
        }
        user.setUpdateId(user.getUserId());//待办
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户（伪删除）
     */
    @DeleteMapping("/deleteById/{userIds}")
    public AjaxResultESDN remove(@PathVariable Long[] userIds) {
        //不能删自己,删除时修改者和修改时间应更新
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 用户登录|验证
     */
    @PostMapping("/login")
    public AjaxResultESDN login(@RequestBody User user) {
        User u;

        //获取用户
        if (UserConstantsESDN.UNIQUE.equals(userService.checkUserUnique(user.getUserId()))) {
            if (UserConstantsESDN.UNIQUE.equals(userService.checkPhoneUnique(String.valueOf(user.getUserId())))) {
                return AjaxResultESDN.error("用户'" + user.getUserId() + "'登录失败，账号不存在");
            }
            else {
                u = userService.selectUserByPhonenumber(String.valueOf(user.getUserId()));
            }
        }
        else {
            u = userService.selectUserById(user.getUserId());
        }

        //账号弃用
        if(u.getUserType()==-1){
            return AjaxResultESDN.error("用户'" + user.getUserId() + "'登录失败，账号已弃用，请联系管理员");
        }

        //账号密码不匹配
        if (!SecurityUtilsESDN.matchesPassword(user.getPassword(), u.getPassword())) {//!u.getPassword().equals(user.getPassword())
            return AjaxResultESDN.error("用户'" + user.getUserId() + "'登录失败，账号或密码错误");
        }
        //获得头像
        u.setAvatar(userService.getUserAvatar(u.getUserId()));
        return AjaxResultESDN.success(u);
    }

    /**
     * 获得收藏夹列表
     *
     * @param userId 用户id
     * @return {@link AjaxResultESDN}
     */
    @GetMapping("/boxroomList")
    public AjaxResultESDN getBoxroomList(Long userId) {
        return boxroomController.getBoxroomList(userId);
    }

    /**
     * 得到未发表博客
     *
     * @param userId 用户id
     * @return {@link AjaxResultESDN}
     */
    @GetMapping("/unpublishedBlogList")
    public AjaxResultESDN getUnpublishedBlogs(Long userId) {
        List<File> blogList=userService.getUnpublishedBlogs(userId);
        return AjaxResultESDN.success(blogList);
    }

    /**
     * 获得上传文件列表
     *
     * @param userId 用户id
     * @return {@link AjaxResultESDN}
     */
    @GetMapping("/myUpload")
    public AjaxResultESDN getUploadFileList(Long userId) throws IOException {
        AjaxResultESDN ajax = AjaxResultESDN.success();
        List<File> fileList = fileService.getUploadFileListByUserId(userId);
        ajax.put(AjaxResultESDN.DATA_TAG, fileList);
        return ajax;
    }

    /**
     * 得到用户id和问题
     *
     * @param phonenumber phonenumber
     * @return {@link AjaxResultESDN}
     */
    @GetMapping("/getUserIdAndQuestion")
    public AjaxResultESDN getUserIdAndQuestion(String phonenumber){
        User user=userService.selectUserByPhonenumber(phonenumber);
        if(user==null){
            return AjaxResultESDN.error("手机号不存在");
        }
        Long userId= user.getUserId();
        String question=userService.selectQuestionByQuestionId(user.getQuestionId());
        //返回
        Map<String,Object> map=new HashMap<>();
        map.put("userId",userId);
        map.put("question",question);
        return AjaxResultESDN.success(map);
    }

    /**
     * 提交密码重置请求（若用户信息正确）
     *
     * @param map 包含userId，phonenumber
     * @return {@code AjaxResultESDN}
     */
    @PostMapping("/submitPasswordResetRequest")
    public AjaxResultESDN submitPasswordResetRequest(@RequestBody HashMap map){
        User user;

        //用户不存在
        try {
            user=userService.selectUserById(Long.parseLong((String) map.get("userId")));
        }catch (Exception e){
            return AjaxResultESDN.error("用户不存在");
        }

        //信息不一致
        if(!user.getPhonenumber().equals(map.get("phonenumber"))){
            return AjaxResultESDN.error("用户信息错误");
        }

        //提交重置请求
        userService.resetPasswordRequest(user.getUserId());
        return AjaxResultESDN.success("重置密码申请已提交");
    }

    /**
     * 获取问题下拉框
     *
     * @return {@link AjaxResultESDN}
     */
    @GetMapping("/getQuestionList")
    public AjaxResultESDN getQuestionList(){
        return AjaxResultESDN.success(userService.selectQuestionList());
    }

    /*
    上传文件列表
    下载文件列表

     */
}
